<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item label="企业身份" prop="type">
            <qc-select
              :value="ruleForm.type"
              :options="optionsS.corporateIdentity"
              placeholder="请选择对账企业身份"
              @change="handleChangeType"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="企业名称" prop="operatorId">
            <qc-select
              ref="optionRef"
              :value="ruleForm.operatorId"
              :remote="true"
              :filterable="true"
              :options="optionsS.orgData"
              placeholder="请选择对账企业"
              @change="handleChangeOrg"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="对账周期" prop="signTime" class="has-tips">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.signTime"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
            <div class="tip">
              <div class="icon"></div>
              平台获取该时间范围内启动充电/支付的订单与互联互通方进行对账，单次对账不超过一年的时间跨度
            </div>
          </el-form-item>
          <el-form-item label="上传对账单" prop="file" class="inline-form">
            <div class="iconfont icon-download" @click="downloadTemplate">
              下载对账模板
            </div>
            <el-upload
              ref="uploadRef"
              class="upload-xls"
              drag
              action="#"
              :auto-upload="true"
              :http-request="uploadFile"
              :before-upload="beforeAvatarUpload"
              :on-remove="onRemove"
              :limit="1"
              :on-exceed="handleExceed"
              accept=".xlsx,.xls"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖至此处或点击此处上传
                <div>支持格式：.xlsx,.xls</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">提交对账</el-button>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import {
  ElMessageBox,
  FormInstance,
  FormRules,
  UploadProps,
} from 'element-plus';
import Head from '@/components/head/index.vue';
import { getFileType } from '@/components/qcUpload/index';
import { queryAllFlow } from '@/service/apis/org';
import { queryDicByParent } from '@/service/apis/api';
import { getDay } from '@/utils/utils';
import {
  reconciliationSave,
  URL_RECONDOWNLOADS,
} from '@/service/apis/financial';

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const optionRef = ref();

let optionsS = reactive({
  orgData: [] as any,
  corporateIdentity: [] as any,
});

let ruleForm = reactive({
  type: [] as any,
  operatorId: [] as any,
  operatorName: [] as any,
  signTime: [] as any,
  file: [] as any,
  startDate: '',
  endDate: '',
});

const rules = reactive<FormRules>({
  operatorId: [
    { required: true, message: '请选择企业名称', trigger: 'change' },
  ],
  type: [{ required: true, message: '请选择企业身份', trigger: 'change' }],
  signTime: [
    {
      required: true,
      message: '请选择对账周期',
      trigger: ['blur', 'change'],
    },
  ],
  file: [{ required: true, message: '请上传对账单', trigger: 'change' }],
});

// 获取企业名称
const handleChangeType = (e: any) => {
  ruleForm.type = e;
  ruleForm.operatorId = [];

  const datas = {} as any;
  if (e == 0) {
    datas.type = e;
    datas.attr = 3;
  } else {
    datas.type = e;
  }
  console.log('datas=-======', datas);

  queryAllFlow(datas).then((res: any) => {
    if (res) {
      optionsS.orgData = res.listMap;
    }
  });
};
const handleChangeOrg = async (e: any) => {
  ruleForm.operatorId = e;
  const operatorNameData = optionsS.orgData.filter(
    (item: any) => item.value == e
  );
  console.log(operatorNameData[0]);
  ruleForm.operatorName =
    operatorNameData.length > 0 ? operatorNameData[0].label : '';
  console.log(ruleForm.operatorName);
};

queryDicByParent({
  listDtos: ['corporateIdentity'],
}).then((res: any) => {
  optionsS.corporateIdentity = res.corporateIdentity.filter(
    (item: any) => item.value !== '1' && item.value !== '3'
  );
});

// 下载模板
const downloadTemplate = () => {
  const url = URL_RECONDOWNLOADS;
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', '');
  a.click(); // 自执行点击事件
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('beforeUpload---', rawFile);
  return getFileType(rawFile, 'xlsx').then((fileType) => {
    // 校验上传类型
    if (!fileType) {
      ElMessageBox.alert('请导入xlsx、xls格式的文件！', '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return false;
    }
    return true;
  });
};
const onRemove: UploadProps['onRemove'] = () => {
  ruleForm.file = [];
  ruleFormRef?.value?.validateField('file');
};
const uploadFile = (data: any) => {
  return new Promise((resolve, reject) => {
    ruleForm.file = [data!.file];
    ruleFormRef?.value?.validateField('file');
  });
};

const handleExceed: UploadProps['onExceed'] = () => {
  ElMessageBox.alert('最多可以上传1个文件', '提示', {
    confirmButtonText: '确认',
    type: 'warning',
  });
};

// 返回
const back = () => {
  router.go(-1);
};

// 新增/修改提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  try {
    await Promise.all([ruleFormRef.value.validate()]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  ruleForm.startDate = getDay(ruleForm.signTime[0]);
  ruleForm.endDate = getDay(ruleForm.signTime[1]);

  const formData = new FormData();

  formData.append('file', ruleForm.file[0]);
  formData.append('startDate', ruleForm.startDate);
  formData.append('endDate', ruleForm.endDate);
  formData.append('type', ruleForm.type);
  formData.append('operatorId', ruleForm.operatorId);
  formData.append('operatorName', ruleForm.operatorName);
  formData.append('channelId', window.localStorage.getItem('channelId') || '');
  formData.append('userId', window.localStorage.getItem('accountId') || '');
  console.log(formData);

  reconciliationSave(formData).then((res: any) => {
    emit('clear-cache');
    back();
  });
};
</script>
  
  <style lang="scss">
.inline-form {
  .el-form-item__content {
    display: block !important;

    .icon-download {
      font-size: 12px;
      color: #5073f7;
      cursor: pointer;
    }

    .upload-xls {
      width: 300px;
    }
  }
}
</style>